// pages/blog/blog.js
var temp_data;
const urlList = require('../resource/js/config.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    'msg': '测试msg',
    imgUrls: [
      'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1556068310&di=08e2d2d88edbe1a1f0188311cf2e05e6&imgtype=jpg&er=1&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F01f1ce5a1525b5a80120518720d7de.jpg%401280w_1l_2o_100sh.jpg',
      'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1556068410&di=4fda49ab80e70fb9b39fbb3d05bde9cc&imgtype=jpg&er=1&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F01d0595a585fc7a80120121feb8226.jpg%401280w_1l_2o_100sh.jpg',
      'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1556068781&di=585e7591d2a3e67e5eddd3484eb579f5&imgtype=jpg&er=1&src=http%3A%2F%2Fs11.sinaimg.cn%2Forignal%2F4aa8e68a043deaf5bcd9a',
      'https://images.unsplash.com/photo-1551334787-21e6bd3ab135?w=640',
      'https://images.unsplash.com/photo-1551214012-84f95e060dee?w=640',
      'https://images.unsplash.com/photo-1551446591-142875a901a1?w=640'
    ],
    id: '',
    items: [],
    title: '',
    pic: '',
    data: {
      result: '',
      charSet: '',
      scanType: '',
      path: ''
    },
    page: 1, // 当前页数
    total_page: 0, // 总页数
    moment: '',
    delBtnWidth: 160,
    isScroll: true,
    windowHeight: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this; //重置data{}里数据时候setData方法的this应为以及函数的this, 如果在下方的sucess直接写this就变成了wx.request()的this了
    wx.showToast({
      title: '加载中',
      icon: 'loading',
      duration: 2000
    }) //设置加载状态框
    let data = {
      page: that.data.page
    }
    wx.request({
      url: urlList.urlList.getBlogListUrl,
      method: "GET",
      header: {
        'content-type': 'application/json' //默认值application/json
      },
      dataType: 'json',
      data: data,
      // data: {
      //   'requestDate': 'wechat app already received'
      // },
      success: result => {
        console.log('请求结果:' + JSON.stringify(result.data));
        if (result.data.status == 200) {
          wx.hideToast(); //请求成功，隐藏提示框
          temp_data = result.data.data.blog;
          console.info('items:' + JSON.stringify(result.data.data.blog)); //res.data相当于ajax里面的data,为后台返回的数据
          // console.log('title:' + result.data.data.blog[0].title);
          //console.log('pic:' + result.data.data.blog[0].pic);
          that.setData({ //如果在sucess直接写this就变成了wx.request()的this了.必须为getdata函数的this,不然无法重置调用函数
            items: temp_data,
            // title: result.data.data.blog[0].title,
            // pic: result.data.data.blog[0].pic
          })
          var tempData = []
          for (let i = 0; i < temp_data.length; i++) {
            let tempObj = {}
            tempObj.id = temp_data[i].id
            tempObj.name = temp_data[i].title
            tempData.push(tempObj)
          }
          //console.log('tempData:' + JSON.stringify(tempData))
        } else {
          console.error('获取数据失败,code:' + result.data.status + '错误信息:' + result.data.msg)
          wx.showToast({
            title: '获取数据失败,code:' + result.data.status + '错误信息:' + result.data.msg,
            icon: 'none',
            duration: 2000
          })
        }

      },
      fail: (result) => {
        console.error('网络异常:', result.errMsg)
        wx.showToast({
          title: '网络异常,' + result.errMsg,
          icon: 'none',
          duration: 2000
        })
      }
    })
    //保留其他页面 跳转 带返回按钮
    // wx.redirectTo({
    //   url: '../blog/blog',
    // });
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          windowHeight: res.windowHeight
        });
      }
    });
  },

  /**
   * es6：()=>
   * es5：function（）{}
   */
  add: () => {
    wx.navigateTo({
      url: '../blog/addblog/addblog',
    })
    // wx.showModal({
    //   title: '提示',
    //   content: '暂不支持emorj表情',
    //   showCancel: true,
    //   confirmText: '我知道了',
    //   confirmColor: '#3A5FCD',
    //   success(res) {
    //     if (res.confirm) {
    //       console.log('用户点击确定')
    //       wx.navigateTo({
    //         url: '../blog/addblog/addblog',
    //       })
    //     } else if (res.cancel) {
    //       console.log('用户点击取消')
    //     }
    //   }
    // })
  },
  seeDetail: res => {
    console.log('调用详情接口:', res)
    wx.request({
      url: urlList.urlList.showDetailUrl + '/' + res.currentTarget.id,
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'GET',
      data: {

      },
      success: res => {
        console.log('获取博客详情成功:', res)
        wx.setStorageSync("blog", JSON.stringify(res.data.blog))
        wx.navigateTo({
          url: '../blog/showdetail/showdetail',
        })
      },
      fail: function(res) {
        console.error(res)
      }
    })
  },
  getScancode: function() {
    var _this = this;
    // 允许从相机和相册扫码
    wx.scanCode({
      success: (res) => {
        var result = res.result;
        var scanType = res.scanType;
        var charSet = res.charSet;
        var path = res.path;
        _this.setData({
          result: result,
          scanType: scanType,
          charSet: charSet,
          path: path
        })
        wx.showToast({
          title: '扫码成功',
          icon: 'success',
          duration: 2000
        })
        wx.setStorageSync("scan", res)
        console.log('扫码成功，跳转页面')
        wx.navigateTo({
          url: '../my/detail/scaninfo',
        })
      },
      fail: (res) => {
        console.error(res.errMsg)
        if (res.errMsg == 'scanCode:fail cancel') {
          wx.showToast({
            title: '取消扫码',
            icon: 'none', //不带icon
            duration: 2000
          })
        } else {
          wx.showToast({
            title: '扫码异常',
            icon: 'none',
            duration: 2000
          })
        }
      },
      complete: (res) => {
        console.log('扫码完成')
        //完成后，隐藏加载框
        //wx.hideLoading()
      }
    })
  },
  loadFuction(e) {
    console.log(e);
    let num = e.currentTarget.id;
    if (num == 0) {
      wx.navigateTo({
        url: '/pages/blog/out', //路径必须跟app.json一致
        success: () => {

        }, //成功后的回调；
        fail: () => {}, //失败后的回调；
        complete: () => {
          console.log('无论成功还是失败，都会执行')
        }
      })
    }

  },
  getQrcode: function() {
    wx.showToast({
      title: '此功能尚未开发',
      icon: 'none',
      duration: 2000
    })
  },
  getFind: function() {
    wx.showToast({
      title: '此功能尚未开发',
      icon: 'none',
      duration: 2000
    })
  },
  getHelp: function() {
    wx.showToast({
      title: '此功能尚未开发',
      icon: 'none',
      duration: 2000
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function(result) {
    //页面渲染完成
    // this.setData({
    //   list: temp_data
    // })
    // var tempData = []
    // for (var i = 0; i < datas.length; i++) {
    //   var tempObj = {}
    //   tempObj.id = datas[i].id
    //   tempObj.name = datas[i].title
    //   tempData.push(tempObj)
    // }
    // console.log('tempData:' + JSON.stringify(tempData))
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    if (getCurrentPages().length != 0) {
      //刷新当前页面的数据
      getCurrentPages()[getCurrentPages().length - 1].onLoad()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   * 关闭所有页面，打开到应用内的某个页面
   */
  onUnload: function() {
    // wx.reLaunch({
    //   url: '../blog/blog',
    // });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   * 下拉刷新
   */
  onPullDownRefresh: function() {
    // 显示顶部刷新图标
    wx.showNavigationBarLoading();
    var that = this;
    wx.request({
      url: urlList.urlList.getBlogListUrl + '?page=' + that.data.page,
      method: "GET",
      header: {
        'content-type': 'application/text'
      },
      success: res => {
        that.setData({
          moment: res.data.data
        });
        // 设置数组元素
        that.setData({
          moment: that.data.moment
        });
        console.log(that.data.moment);
        // 隐藏导航栏加载框
        wx.hideNavigationBarLoading();
        // 停止下拉动作
        wx.stopPullDownRefresh();
      }
    })
    // setTimeout(() => { // 模拟请求数据，并渲染 
    //   wx.stopPullDownRefresh();
    // }, 1000);
  },

  /**
   * 页面上拉触底事件的处理函数
   * 上拉加载更多
   */
  onReachBottom: function() {
    var that = this;
    // 显示加载图标
    wx.showLoading({
      title: '玩命加载中',
    })
    if (that.data.page > that.data.total_page) {
      console.log('没有更多数据了:' + that.data.page)
      wx.showToast({
        title: '没有更多数据了！',
        icon: 'none',
        duration: 2000
        //image: '../resource/images/error.png',
      })
    } else {
      wx.request({
        url: urlList.urlList.getBlogListUrl + '?page=' + that.data.page + 1, // 页码+1
        method: "GET",
        header: {
          'content-type': 'application/text'
        },
        success: function(res) {
          // 回调函数
          var moment_list = that.data.moment;
          for (var i = 0; i < res.data.data.length; i++) {
            moment_list.push(res.data.data[i]);
          }
          // 设置数据
          that.setData({
            moment: that.data.moment
          })
          wx.hideLoading();
          wx.showToast({
            title: '加载完成',
            icon: 'none',
            duration: 2000
          })
        },
        fail: (err) => {
          wx.hideLoading(); // 隐藏加载框
          console.error('网络异常:', err)
          wx.showToast({
            title: '网络异常,' + err.errMsg,
            icon: 'none',
            duration: 2000
          })
        }
      })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    return {
      title: '微信小程序',
      desc: '微信小程序学习!',
      path: '/pages/start/start'
    }
  },
  drawStart: function(e) {
    // console.log("drawStart");  
    var touch = e.touches[0]

    for (var index in this.data.items) {
      var item = this.data.items[index]
      item.right = 0
    }
    this.setData({
      items: this.data.items,
      startX: touch.clientX,
    })

  },
  drawMove: function(e) {
    var touch = e.touches[0]
    var item = this.data.items[e.currentTarget.dataset.index]
    var disX = this.data.startX - touch.clientX

    if (disX >= 20) {
      if (disX > this.data.delBtnWidth) {
        disX = this.data.delBtnWidth
      }
      item.right = disX
      this.setData({
        isScroll: false,
        items: this.data.items
      })
    } else {
      item.right = 0
      this.setData({
        isScroll: true,
        items: this.data.items
      })
    }
  },
  drawEnd: function(e) {
    var item = this.data.items[e.currentTarget.dataset.index]
    if (item.right >= this.data.delBtnWidth / 2) {
      item.right = this.data.delBtnWidth
      this.setData({
        isScroll: true,
        items: this.data.items,
      })
    } else {
      item.right = 0
      this.setData({
        isScroll: true,
        items: this.data.items,
      })
    }
  },

  delItem: function(res) {
    let id = res.currentTarget.id
    console.log('删除：' + id)
    wx.showModal({
      title: '提示',
      content: '确认删除吗？',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          wx.request({
            url: urlList.urlList.del + '/' + id,
            header: {
              'content-type': 'application/json'
            },
            method: 'GET',
            data: id,
            success: res => {
              console.log('请求结果res:', res)
              if (res.data.status == 200) {
                wx.showToast({
                  title: '删除成功，' + id,
                  icon: 'none',
                  duration: 2000,
                  mask: true,
                  success: function() {
                    // 删除成功，返回博客列表页，并刷新博客列表页
                    setTimeout(function() {
                      // 刷新页面
                      wx.reLaunch({
                        url: '../blog/blog',
                      });
                    }, 2000)
                  }
                })
              } else {
                console.error('删除博客失败:', res)
                console.error('删除失败，code:' + res.data.status + '错误信息:' + res.data.msg)
                wx.showToast({
                  title: '删除失败，code:' + res.data.status + '错误信息:' + res.data.msg,
                  icon: 'none',
                  duration: 2000
                })
              }
            },
            fail: (err) => {
              console.error('网络异常:', err)
              wx.showToast({
                title: '网络异常,' + err.errMsg,
                icon: 'none',
                duration: 2000
              })
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  }
})